package com.telit.android.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.telit.android.dao.CommEventTaskTrackDao;
import com.telit.android.dto.PatrolTaskDTO;
import com.telit.android.service.ICommEventTaskTrackService;
import com.telit.common.core.utils.FeignUtils;
import com.telit.common.entity.CommEventTaskTrack;
import com.telit.common.vo.SysRoleEntity;
import com.telit.firecommand.feign.RemoteFirecommandService;
import com.telit.upms.feign.RemoteUpmsService;
import com.telit.upms.vo.MicroSysUserAllInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * 事件任务巡护关联表 服务实现类
 * </p>
 *
 * @author yummy
 * @since 2021-07-26
 */
@Service
@Transactional
public class CommEventTaskTrackServiceImpl extends ServiceImpl<CommEventTaskTrackDao, CommEventTaskTrack> implements ICommEventTaskTrackService {

    @Autowired
    private RemoteFirecommandService fireCommandFeignClient;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RemoteUpmsService remoteUpmsService;

    @Override
    public int add(CommEventTaskTrack commEventTaskTrack) {
        return baseMapper.insert(commEventTaskTrack);
    }

    @Override
    public int delete(Integer id) {
        return baseMapper.deleteById(id);
    }

    @Override
    public List<Integer> deleteBatch(Integer[] ids) {
        List<Integer> values = new ArrayList<Integer>();
        if (ids != null && ids.length > 0) {
            for (Integer id : ids) {
                values.add(delete(id));
            }
        }
        return values;
    }

    @Override
    public int updateData(CommEventTaskTrack commEventTaskTrack) {
        return baseMapper.updateById(commEventTaskTrack);
    }

    @Override
    public CommEventTaskTrack findById(Integer id) {
        return baseMapper.selectById(id);
    }


    @Override
    public IPage<CommEventTaskTrack> findListByPage(CommEventTaskTrack commEventTaskTrack, Integer page, Integer pageCount) {
        IPage<CommEventTaskTrack> commEventTaskTrackPage = new Page<>(page, pageCount);
        QueryWrapper<CommEventTaskTrack> wrapper = new QueryWrapper<>();
        if (commEventTaskTrack != null) {
            if (StringUtils.hasText(commEventTaskTrack.getEventType())) {
                wrapper.eq("event_type", commEventTaskTrack.getEventType());
            }
            if (StringUtils.hasText(commEventTaskTrack.getHotPortNumber())) {
                wrapper.eq("hot_port_number", commEventTaskTrack.getHotPortNumber());
            }
            if (StringUtils.hasText(commEventTaskTrack.getCountryCode())) {
                wrapper.eq("country_code", commEventTaskTrack.getCountryCode());
            }
            if (StringUtils.hasText(commEventTaskTrack.getTrackType())) {
                wrapper.eq("track_type", commEventTaskTrack.getTrackType());
            }
            if (StringUtils.hasText(commEventTaskTrack.getStatus())) {
                wrapper.eq("status", commEventTaskTrack.getStatus());
            }
        }
        return baseMapper.selectPage(commEventTaskTrackPage, wrapper);
    }

    @Override
    public List<CommEventTaskTrack> searchNoPage(CommEventTaskTrack commEventTaskTrack) {
        QueryWrapper<CommEventTaskTrack> wrapper = new QueryWrapper<>();
        if (commEventTaskTrack != null) {
            if (StringUtils.hasText(commEventTaskTrack.getEventType())) {
                wrapper.eq("event_type", commEventTaskTrack.getEventType());
            }
            if (StringUtils.hasText(commEventTaskTrack.getHotPortNumber())) {
                wrapper.eq("hot_port_number", commEventTaskTrack.getHotPortNumber());
            }
            if (StringUtils.hasText(commEventTaskTrack.getCountryCode())) {
                wrapper.eq("country_code", commEventTaskTrack.getCountryCode());
            }
            if (StringUtils.hasText(commEventTaskTrack.getTrackType())) {
                wrapper.eq("track_type", commEventTaskTrack.getTrackType());
            }
            if (StringUtils.hasText(commEventTaskTrack.getStatus())) {
                wrapper.eq("status", commEventTaskTrack.getStatus());
            }
        }
        return baseMapper.selectList(wrapper);
    }


    @Override
    public List<CommEventTaskTrack> selectTaskingByUserId(List<Long> foresterIds, String status) {
        return baseMapper.selectByTaskingByForesterId(foresterIds, status);
    }

    @Override
    public List<PatrolTaskDTO> patrolTaskByFireId(Long fireId) {
        //2022-05-18 优化避免重复调用 ----------- fixed by yzx----------------------start
      /*  List<PatrolTaskDTO> patrolTaskList = baseMapper.patrolTaskByFireId(fireId);
        if(!CollectionUtils.isEmpty(patrolTaskList)){
            patrolTaskList.forEach(patrolTaskDTO -> {
                // 返回完整图片路径信息
                if(!StringUtils.isEmpty(patrolTaskDTO.getMediaUrl())){
                    List<String> mediaList = JSON.parseArray(patrolTaskDTO.getMediaUrl(),String.class);
                    List<String> newMediaList = new ArrayList<>();
                    mediaList.forEach(mediaUrl -> newMediaList.add(MinioUtils.previewImg(mediaUrl)));
                    patrolTaskDTO.setMediaUrlList(newMediaList);
                }
                // 调用统一平台获取用户名
                SysUserDetailVo sysUserVo = userInfoService.getUserInfo(patrolTaskDTO.getForesterId());
                patrolTaskDTO.setForesterName(sysUserVo == null?null:sysUserVo.getRealName());
            });
        }*/

        final List<PatrolTaskDTO> patrolTaskList = baseMapper.patrolTaskByFireId(fireId);
        if (CollUtil.isEmpty(patrolTaskList)) {
            return CollUtil.newArrayList();
        }
        //获取 ids 集合
        final List<Long> ids = patrolTaskList.stream()
                //过滤空id
                .filter(patrolTaskDTO -> ObjectUtil.isNotEmpty(patrolTaskDTO.getForesterId()))
                .map(PatrolTaskDTO::getForesterId)
                //id去重
                .distinct()
                .collect(Collectors.toList());
      //  final List<SysUserDetailVo> vos = userInfoService.queryUserInfoByIds(ids);
        com.telit.common.core.utils.Result<Map<Long, MicroSysUserAllInfoVo>> selectUserContainDeptAndRoleWithBatchIdsResult = remoteUpmsService.selectUserContainDeptAndRoleWithBatchIds(
                ids, true);
        Map<Long, MicroSysUserAllInfoVo> longMicroSysUserAllInfoVoMap = FeignUtils.unwrap(
                selectUserContainDeptAndRoleWithBatchIdsResult);

        List<MicroSysUserAllInfoVo> vos = ids.stream().map(
                longMicroSysUserAllInfoVoMap::get).collect(Collectors.toList());

        //构造id和名称关系
        final Map<Long, String> idNameMapping = Maps.newHashMap();
        if (CollUtil.isNotEmpty(vos)) {
            idNameMapping.putAll(vos.stream().collect(Collectors.toMap(MicroSysUserAllInfoVo::getId, MicroSysUserAllInfoVo::getRealName)));
        }
        patrolTaskList.forEach(patrolTaskDTO -> {
            // 返回完整图片路径信息
            if (!StringUtils.isEmpty(patrolTaskDTO.getMediaUrl())) {
                List<String> mediaList = JSON.parseArray(patrolTaskDTO.getMediaUrl(), String.class);
                patrolTaskDTO.setMediaUrlList(mediaList);
            }
            // 调用统一平台获取用户名
            final String forestName = ObjectUtil.defaultIfNull(idNameMapping.get(patrolTaskDTO.getForesterId()), StrUtil.EMPTY);
            patrolTaskDTO.setForesterName(forestName);
        });

        //2022-05-18 优化避免重复调用 ----------- fixed by yzx----------------------end
        return patrolTaskList;
    }

    @Override
    public void updateCommEventTaskTrackByParam(CommEventTaskTrack commEventTaskTrack) {
        baseMapper.update(new CommEventTaskTrack().setTrackId(commEventTaskTrack.getTrackId()).setStatus(commEventTaskTrack.getStatus()),
                new QueryWrapper<CommEventTaskTrack>().eq("task_id", commEventTaskTrack.getTaskId()).eq("forestkeeper_id", commEventTaskTrack.getForestkeeperId()));
    }

    @Override
    public List<Long> selectIdByTaskIdAndStatus(Long taskId, String status, Long forestkeeperId) {
        return baseMapper.selectIdByTaskIdAndStatus(taskId, status, forestkeeperId);
    }

    private List<String> getRoleCodeList(List<SysRoleEntity> list) {
        List<String> codeList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(role -> codeList.add(role.getCode()));
        }
        return codeList;
    }
}
